<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="时间查询">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="单据编号" prop="billNumber">
        <el-input
          v-model="queryParams.billNumber"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户姓名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="团队查询" prop="deptId">
        <treeselect style="width: 215px" v-model="queryParams.deptId" :options="deptOptions" :show-count="true"
                    placeholder="请选择团队"/>
      </el-form-item>
      <el-form-item label="是否审核" prop="examStatus">
        <el-select v-model="queryParams.examStatus" placeholder="请选择是否审核" clearable>
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['data:sale:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table stripe border v-loading="loading" :data="saleList" @selection-change="handleSelectionChange"
              @sort-change="tableSortChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键" align="center" prop="id" v-if="false"/>
      <el-table-column label="单据编号" align="center" prop="billNumber"/>
      <el-table-column label="用户姓名" align="center" prop="nickName"/>
      <el-table-column label="总金豆" align="center" prop="allGold"/>
      <el-table-column label="增加名额" align="center" prop="addUser"/>
      <el-table-column label="总数量" align="center" prop="allAmount"/>
      <el-table-column label="审核状态" align="center" prop="examStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.examStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="examName"/>
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="100" sortable/>
      <el-table-column label="审核时间" align="center" prop="examTime" min-width="100" sortable/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="primary"
            plain
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['data:sale:edit']"
          >查看订单
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-row :gutter="15">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="单据编号" prop="billNumber">
                <el-input v-model="form.billNumber" placeholder="单据编号自动生成" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="会员姓名" prop="nickName">
                <el-input v-model="form.nickName" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报货人" prop="stockNickName">
                <el-input v-model="form.stockNickName" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总金豆" prop="allGold">
                <el-input v-model="form.allGold" placeholder="自动计算" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="增加名额" prop="addUser">
                <el-input v-model="form.addUser" placeholder="自动计算" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总数量" prop="allAmount">
                <el-input v-model="form.allAmount" placeholder="自动计算" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input :rows="4" v-model="form.remark" type="textarea" placeholder="请输入备注" readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-divider content-position="center">订单明细信息</el-divider>
            </el-col>
          </el-row>
          <el-table :data="dataSaleItemList" :row-class-name="rowDataSaleItemIndex" ref="dataSaleItem" show-summary>
            <el-table-column label="序号" align="center" prop="index" width="50"/>
            <el-table-column label="商品代码" prop="goodCode" width="150"/>
            <el-table-column label="商品名称" prop="goodName" width="auto"/>
            <el-table-column label="金豆数量" prop="goldAmount" width="150"/>
            <el-table-column label="商品数量" prop="goodAmount" width="150"/>
          </el-table>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="examForm" v-if="form.examStatus === 'N'">审 核</el-button>
        <el-button type="danger" @click="cancelForm" v-if="form.examStatus === 'Y'">撤 销</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {cancelSale, examSale, getSale, listSale} from "@/api/data/sale";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {deptTreeSelect} from "@/api/system/user";
import {parseTime} from "@/utils/ruoyi";

export default {
  name: "BillExam",
  dicts: ['sys_type', 'sys_yes_no'],
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单信息表格数据
      saleList: [],
      // 订单明细表格数据
      dataSaleItemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: null,
        isAsc: null,
        deptId: null,
        userId: null,
        nickName: null,
        allGold: null,
        addUser: null,
        allAmount: null,
        examStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        nickName: [
          {required: true, message: "请选择会员", trigger: "blur"}
        ],
      },
      // 代理树选项
      deptOptions: undefined,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近六个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 182);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一整年',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 日期范围
      dateRange: [parseTime(new Date().setDate(1), '{y}-{m}-{d}'), parseTime(new Date(), '{y}-{m}-{d}')],
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    /** 查询代理下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询订单信息列表 */
    getList() {
      this.loading = true;
      listSale(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.saleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        billNumber: null,
        deptId: null,
        userId: null,
        nickName: null,
        allGold: null,
        addUser: null,
        allAmount: null,
        examStatus: 'N',
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.dataSaleItemList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [parseTime(new Date().setDate(1), '{y}-{m}-{d}'), parseTime(new Date(), '{y}-{m}-{d}')]
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 通用排序 */
    tableSortChange(column) {
      this.queryParams.pageNum = 1
      if (column.order === 'descending') {
        this.queryParams.orderByColumn = column.prop
        this.queryParams.isAsc = 'desc'
      } else if (column.order === 'ascending') {
        this.queryParams.orderByColumn = column.prop
        this.queryParams.isAsc = 'asc'
      } else {
        this.queryParams.orderByColumn = undefined
        this.queryParams.isAsc = undefined
      }
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSale(id).then(response => {
        this.form = response.data;
        this.dataSaleItemList = response.data.dataSaleItemList;
        this.open = true;
        this.title = "审核订单信息";
      });
    },
    /** 审核按钮 */
    examForm() {
      let that = this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$modal.confirm('是否审核订单').then(function () {
            examSale(that.form).then(response => {
              that.$modal.msgSuccess("审核成功");
              that.open = false;
              that.getList();
            });
          })
        }
      });
    },
    /** 撤销按钮 */
    cancelForm() {
      let that = this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$modal.confirm('是否撤销订单').then(function () {
            cancelSale(that.form).then(response => {
              that.$modal.msgSuccess("撤销成功");
              that.open = false;
              that.getList();
            });
          })
        }
      });
    },
    /** 订单明细序号 */
    rowDataSaleItemIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('data/sale/export', {
        ...this.queryParams
      }, `sale_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
